/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedModelData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { isEmpty } from 'lodash';
import { useEffect, useState } from 'react';

type FormDataType = {
  mode: string;
  base: pickedModelData;
  tool: pickedModelData[];
};

type Params = {
  mode: string;
  base: string;
  tool: string[];
};

function BoolDialog({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData = {
    mode: 'fuse',
    base: null,
    tool: [],
  };
  const [formData, setFormData] = useState<FormDataType>(initData);

  const { picker } = useTools();

  useEffect(() => {
    if (!props?.params) {
      setFormData(initData);
      return () => {};
    }

    const params: Params = props.params;
    const { tool, mode, base } = params;
    (async () => {
      await initEditDependency([...tool, base]);

      setFormData({
        tool: tool.map(
          (i) => picker.generatePickObjByPickID(i) as pickedModelData,
        ),
        base: picker.generatePickObjByPickID(base) as pickedModelData,
        mode: mode,
      });
    })();
  }, [props?.shape]);

  const checkAndFinishDraw = async () => {
    const { base, tool } = formData;
    if (isEmpty(base) || isEmpty(tool)) return;

    await execute(false);
    onClose();
  };

  useAsyncEffect(async () => {
    execute(true);
  }, [formData]);

  const execute = async (preview: boolean) => {
    const { mode, base, tool } = formData;
    if (isEmpty(base) || isEmpty(tool)) {
      clear();
      return;
    }

    const baseData = base?.assisObj?.modelDxid;
    const toolData = tool.map((i) => i.assisObj.modelDxid);

    if (baseData != null && toolData.includes(baseData)) {
      MessageTip.error('工具体中不能包含基准模型');
      clear();
      return;
    }

    const params = {
      a: {
        mode: mode,
        base: baseData,
        tool: toolData,
      },
    };

    await confirmCommand(params, preview);
  };

  const isFormDataValid = () => {
    const { mode, base, tool } = formData;
    return mode !== null && base !== null && tool?.length > 0;
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      mode: {
        type: 'string',
        title: '模式',
        default: 'fuse',
        oneOf: [
          {
            type: 'string',
            title: '布尔添加',
            const: 'fuse',
          },
          {
            type: 'string',
            title: '布尔移除',
            const: 'cut',
          },
          {
            type: 'string',
            title: '布尔相交',
            const: 'common',
          },
        ],
      },
      base: {
        type: 'string',
        title: '基准模型',
        format: PickInputRJSFFormat.PickModel,
      },
      tool: {
        type: 'array',
        items: {
          type: 'string',
          enum: [],
        },
        title: '工具模型',
        uniqueItems: true,
        format: PickInputRJSFFormat.MultiPickModel,
      },
    },
  };

  const { initEditDependency, initingEdit, isLoading, confirmCommand, clear } =
    useCommand('cmd-boolean', {
      commandName: 'CreateBoolean',
      editDxid: props?.shape,
      dependencies: props?.params
        ? props.params.tool.concat(props.params.base)
        : [],
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  return (
    <PickableCommandForm
      disabled={initingEdit}
      submitLoading={isLoading}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData({
          mode: v?.mode,
          base: v?.base,
          tool: v?.tool,
        });
      }}
      extraUiSchema={{
        base: {
          'ui:placeholder': '请输入体',
          'ui:autofocus': true,
        },
        tool: {
          'ui:placeholder': '请输入体',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdBoolean: CurvedBaseCommand = {
  id: 'cmdBoolean',
  label: 'command.boolean',
  icon: 'commands/curved/boolean',
  create: (label: string, onClose: () => void, props: any) => (
    <BoolDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
